package com.woniuxy.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.user.entity.UserAccount;
import com.woniuxy.user.entity.UserInfo;
import com.woniuxy.user.service.exception.RealNameException;
import com.woniuxy.user.service.exception.UserException;
import com.woniuxy.user.mapper.UserAccountMapper;
import com.woniuxy.user.mapper.UserInfoMapper;
import com.woniuxy.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.user.dto.RealNameDto;
import com.woniuxy.user.dto.UserInfoDto;
import com.woniuxy.user.form.RealNameForm;
import com.woniuxy.user.form.UpdateUserInfoForm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAccountMapper userAccountMapper;

    /**
     * 修改个人信息
     * @param userId 用户id
     * @param form 完善用户信息参数
     */
    @Override
    public void updateUserInfo(Integer userId,UpdateUserInfoForm form) {
        UserInfo userInfo = this.getOne(new QueryWrapper<UserInfo>().eq("user_id", userId));
        userInfo.setNickName(form.getNickName());
        this.updateById(userInfo);
        UserAccount userAccount = userAccountMapper.selectById(userId);
        userAccountMapper.updateById(userAccount);
    }

    /**
     * 返回实名结果
     * @param is 流
     * @return
     * @throws IOException
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    /**
     * 实名认证
     * @param userId 用户ID
     * @param form 实名认证参数
     * @throws IOException
     */
    @Override
    public void realName(Integer userId,RealNameForm form) throws IOException {

        UserAccount userAccount = userAccountMapper.selectById(userId);
        if(userAccount==null) throw new UserException(10001,"用户不存在");
        if(this.getById(userId).getIsReal()==1) throw new RealNameException(10006,"用户已经实名");
        UserInfo info = this.getOne(new QueryWrapper<UserInfo>().eq("id_card", form.getIdCard()));
        if(info!=null) throw new UserException(10001,"该身份证号已被实名");
        String host = "https://idcert.market.alicloudapi.com"; // 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/idcard";// 【2】后缀
        String appcode = "48ecb6d136e7404a9f3f22c01370b120"; // 【3】开通服务后 买家中心-查看AppCode
        String idCard = form.getIdCard();// 【4】请求参数，详见文档描述
        String name = form.getRealName();// 【4】请求参数，详见文档描述
            String urlSend = host + path + "?idCard=" + idCard + "&name="+ URLEncoder.encode(name, "UTF-8");// 【5】拼接请求链接
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);//格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                RealNameDto realNameDto = JSONUtil.toBean(json, RealNameDto.class);
                if(realNameDto.getStatus()!=01) throw new RealNameException(10001,"实名认证失败");
                UserInfo userInfo = this.getById(userId);
                userInfo.setUserBirthday(realNameDto.getBirthday());
                userInfo.setRealName(form.getRealName());
                userInfo.setIsReal(1);
                userInfo.setIdCard(form.getIdCard());
                this.updateById(userInfo);
            } else {
                throw new RealNameException(10002,"支付宝实名认证接口出错");
            }
    }

    /**
     * 更新用户头像
     * @param userId 用户id
     * @param filePath 路径
     */
    @Override
    public void updateUserHeader(Integer userId, String filePath) {
        UserInfo userInfo = this.getOne(new QueryWrapper<UserInfo>().eq("user_id", userId));
        userInfo.setUserHeader(filePath);
        this.updateById(userInfo);
    }

    /**
     * 分页查询所有用户
     * @param pageNum 当前页
     * @param pageSize 每页几条
     * @return
     */
    @Override
    public Page<UserInfoDto> loadAllUserInfo(Integer pageNum, Integer pageSize,String condition) {
      Page<UserInfo>page=new Page<>(pageNum,pageSize);
      QueryWrapper<UserInfo>wrapper=new QueryWrapper<>();
      if(condition!=null&&condition!=""){
          wrapper.like("nick_name",condition);
          wrapper.or();
          wrapper.like("real_name",condition);
      }
      this.page(page,wrapper);
      List<UserInfoDto>dtos=new ArrayList<>();
      List<UserInfo> list = page.getRecords();
        if (list!=null&&list.size()>0) {
            for (UserInfo userInfo : list) {
                UserInfoDto dto = BeanUtil.toBean(userInfo, UserInfoDto.class);
                UserAccount userAccount = userAccountMapper.selectById(dto.getUserId());
                dto.setState(userAccount.getState());
                dto.setUserName(userAccount.getUserName());
                dto.setUserPhone(userInfo.getUserPhone());
                dtos.add(dto);
            }
        }
        Page<UserInfoDto>pages=new Page<>();
        pages.setTotal(page.getTotal());
        pages.setPages(page.getPages());
        pages.setCurrent(page.getCurrent());
        pages.setSize(page.getSize());
        pages.setRecords(dtos);
        return pages;
    }

    /**
     * 根据ID查询用户信息
     * @param userId 用户id
     * @return
     */
    @Override
    public UserInfoDto findUserInfoById(Integer userId) {
        UserInfo userInfo = this.getOne(new QueryWrapper<UserInfo>().eq("user_id", userId));
        if(userInfo==null) throw new UserException(2001,"用户不存在");
        UserInfoDto dto = BeanUtil.toBean(userInfo, UserInfoDto.class);
        UserAccount userAccount = userAccountMapper.selectById(userId);
        dto.setUserPhone(userInfo.getUserPhone());
        dto.setUserName(userAccount.getUserName());
        dto.setState(userAccount.getState());
        return dto;
    }
}
